package file

import (
	beego "github.com/beego/beego/v2/server/web"
	"os"
	"strconv"
	"strings"
	"time"
	"xpms/controllers"
	"xpms/cores/utils"
)

// 文件上传
type UploadFileController struct {
	controllers.BaseController
}

// @Title  单上传文件
// @Description  单上传文件
// @Accept multipart/form-data
// @Param file formData file true "file"
// @Success 200 {string}
// @Failure 403 body is empty
// @router / [post]
func (c *UploadFileController) Post() {
	//imgFile
	f, h, err := c.GetFile("file")
	if err != nil {
		c.Data["json"] = map[string]interface{}{"code": 0, "message": "目录权限不够"}
		c.ServeJSON()
		return
	}
	defer f.Close()
	//生成上传路径
	now := time.Now()
	// 创建上传文件目录
	uploadDir := "/uploadfile/" + strconv.Itoa(now.Year()) + "-" + strconv.Itoa(int(now.Month())) + "/" + strconv.Itoa(now.Day())
	tmpDir := utils.GetGuid()
	StaticPath, err := beego.AppConfig.String("StaticPath")
	if err != nil {
		c.Data["json"] = map[string]interface{}{"error": 1, "message": "未配置目录"}
		c.ServeJSON()
		return
	}
	mkdir := StaticPath + uploadDir + "/" + tmpDir
	err1 := os.MkdirAll(mkdir, 0755)
	if err1 != nil {
		c.Data["json"] = map[string]interface{}{"error": 1, "message": "目录权限不够"}
		c.ServeJSON()
		return
	}
	//生成新的文件名
	filename := h.Filename
	//ext := utils.SubString(filename, strings.LastIndex(filename, "."), 5)
	//ext := path.Ext(h.Filename)
	//ext := utils.SubString(utils.Unicode(filename), strings.LastIndex(utils.Unicode(filename), "."), 5)
	if err != nil {
		c.Data["json"] = map[string]interface{}{"error": 1, "message": err}
	} else {
		// 构建访问文件路径
		fpath := "/file" + uploadDir + "/" + tmpDir
		c.SaveToFile("file", mkdir+"/"+filename)
		url := strings.Replace(fpath, ".", "", 1) + "/" + filename
		c.Data["json"] = map[string]interface{}{"error": 0, "url": url, "filename": filename}
	}
	c.ServeJSON()
}
